﻿/// <reference path="../jquery-easyui-1.2.6/jquery-1.7.2.min.js" />
;(function ($) {
    $.fn.extend({
           caculateTable: function(config) {
            return this.each(function() {
                new $.CaculateTable(this, config);
            });
        }
    });
    
    //stock in all list
    var storageCache =new Array;   //all stock in list
    var defaultConfig ={countRow:true,totalSum:totalSummary,dataCache:true,"delRow": true}; //default seting
    var totalSummary ={orderCount:0,totalmoney:0,totalCount:0}; //footer data
    var colSummray  = [];

    //extend array
    Array.prototype.moveAt = function(index)
    {
        var newArr = [];
        if(this.length<1) return this;
        if(this.length<index||index<0) return this;
        
        for(var i=0,arrLen= this.length;i<arrLen;i++)
        {
           if(i!=index)
             newArr.push(this[i])
        }
        return newArr;
    }

    Array.prototype.hasObjPropValue = function(prop,value){
        var has = false;
        for(var i=0,arrLen= this.length;i<arrLen;i++)
        {
            if( this[i][prop])
            {
               if(this[i][prop] == value)
               {
                 has = true;
                 break;
               }
            }
        }
        return has;
    }

    $.CaculateTable = function (table, config) {
        var config = jQuery.extend(defaultConfig, config || {});
        
        //Td bind json data
        if(config["datalist"])
        {
           addRow(config["datalist"]);
        }
       // Allow to delete rows
        if (config['delRow']) 
        {
          $(table).find('a').each(function(){
              jQuery(this).unbind('click').bind("click", function () {
                delRow(this); 
                return true;
                });
            });
        }

         //operate col
         function getColsSammary(){
           var th = $(table).find("tr").first();
           // console.log(th);
           var colArr = new Array;
           th.find("td").each(function(index,elem){
             var smy = $(elem).attr("summary")
             if(smy){
                var colsumy = {colIndex:index,summary:smy};
                colArr.push(colsumy);
             }
           });
           return colArr;
        }

        //Allow to add row
        function addRow(data){
           if(config["cannotRepterCol"])
           {
               var colAtr =config["cannotRepterCol"];
               if(storageCache.hasObjPropValue(colAtr,data[colAtr]))
               {
                   alert("你已经扫描过条码"+data[colAtr]+"信息了");
                   return;
               }
           }
           storageCache.push(data);
           var trs = $(table).find("tr");
           var item =trs.length-1;
           var trStr ="<tr row='"+item+"'>";
           trStr+="<td>"+item+"</td>";
           for(var prop in data)
           {
              if(data.hasOwnProperty(prop))
              {
                 //console.log(data[prop]);
                    trStr+="<td>"+data[prop]+"</td>";
             }
           }
           trStr +="<td><a id='delete' href='#'>删除</a>";
           trStr+="</tr>";
           trs.eq(trs.length-2).after(trStr);          
           //console.log(trStr);
           calculateSummary(); 
           if(config["cacheData"])
             setStorageDataToHidden();
        }
        
        function setTableFoot()
        {
            var trs = $(table).find("tr");
            trs.last().find("td").eq(0).html("");
            trs.last().find("td").eq(0).html(" <span>合计 "+totalSummary.orderCount+"笔</span>");

            trs.last().find("td").eq(1).html("");
            trs.last().find("td").eq(1).html(" <span>数量合计 "+totalSummary.totalCount+"</span>");

            trs.last().find("td").eq(2).html("");
            trs.last().find("td").eq(2).html(" <span>合计 "+totalSummary.totalmoney.toFixed(2)+"￥</span>");
        }

        //delete Rows
        function delRow(elem){
          
          if(!confirm("确定要删除该信息吗?")){
             return;
          }
          var dRow = $(elem).parents('tr').eq(0);
          var rowItem = dRow.find("td").eq(0).html();
          dRow.remove();
           //set coutRows
           var trs = jQuery(table).find("tr");
           var trsLen = trs.length-1;
           trs.slice(1,trsLen).find("td:nth-child(1)").each(function(index,elem){
              $(elem).html(index+1); 
           });  
           //new cacultor
          calculateSummary();
          var sto = storageCache.moveAt(parseInt(rowItem)-1);
          //storage cache data
        
          storageCache.splice(0,this.length);
          storageCache = sto;
          if(config["cacheData"])
            setStorageDataToHidden();
           //console.log("del");
        }

        //calculate Summary
        function calculateSummary()
        {
           //(1)total rows 
           var trs = $(table).find("tr");
           totalSummary.orderCount= trs.length-2>0?trs.length-2:0;
           //(2) caculator summary col,don't compute NotNum
           colSummray = getColsSammary();
           if(colSummray.length<1){
              totalSummary.totalmoney = 0;
              totalSummary.totalCount=0;
           }
           else{
              var reg =/^\d+(\.\d+)?$/;
              var operate;
              var res = 0, sum = 0,unitCont=0;
              for(var i=0,len= colSummray.length;i<len;i++)
              { 
                   operate = colSummray[i].summary;
                   var trs = $(table).find("tr");
                   trs.each(function(index,elem){
                   var val = $(elem).find("td").eq(colSummray[i].colIndex).html()||"";
                     if(reg.test(val)){
                         if(colSummray[i].colIndex==5){
                          if(operate=="sum")
                              unitCont+=val*1;
                           }
                        if(colSummray[i].colIndex==7){
                              if(operate=="sum")
                                sum+=val*1;   
                           }
                       }
                     if(operate=="sum")
                     {
                        totalSummary.totalmoney = rs = sum;
                        totalSummary.totalCount=unitCont;
                     }
                   });
              }
           } 
           setTableFoot();   
        }

        //set storage hidden value
        function setStorageDataToHidden()
        {
           var id = document.getElementById(config["cacheHtmlId"]);
            var hidHtml = $("#"+config["cacheHtmlId"]);
            if(id){
               hidHtml.data("storagedata",storageCache);
            }
        }
        

        //refresh datatable
        function reRefresh(){
        }
    }
})(jQuery);



